const mongoose = require('mongoose')
const bcrypt = require('bcrypt')
const Schema = mongoose.Schema
const SALT_WORK_FACTOR = 10

const UserSchema = new Schema({
    username:{
        type:String,
        unique:true,
        required:true
    },
    password:{
        type:String,
        required:true,
        maxlength:12,
        minlength:6
    },
    email:{
        type:String,
        required:true
    },
    sex:{
        type:String,
        enum:['male','female'],
        default:'male'
    },
    meta:{
        createdAt:{
            type:Date,
            default:Date.now()
        },
        updatedAt:{
            type:Date,
            default:Date.now()
        }
    }
})

UserSchema.pre('save',function(next){
    if(this.isNew){
        this.meta.createdAt = this.meta.updatedAt = Date.now()
    }else{
        this.meta.updatedAt = Date.now()
    }
    next()
})

UserSchema.pre('save',function(next){
    if(!this.isModified('password')){
        return next()
    }
    bcrypt.genSalt(SALT_WORK_FACTOR,(err,salt)=>{
        if(err) next()
        bcrypt.hash(this.password,salt,(err,hash)=>{
            if(err) next()
            this.password = hash
            next()
        })
    })
})

UserSchema.methods = {
    comparePassword:function(_password,password){
        return new Promise((resolve,reject)=>{
            bcrypt.compare(_password,password,(err,sname)=>{
                if(err) reject(err)
                else resolve(sname)
            })
        })
        
    }
}

mongoose.model('user',UserSchema,'user') //执行这里会在数据库中创建一个名叫user的collection